package com.zhoug.demo.player.http;


import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zhoug.common.http.core.ContentType;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


/**
 * token拦截器
 *
 * @Author HK-LJJ
 * @Date 2019/12/6
 * @Description
 */
public class TokenInterceptor implements Interceptor {
    private static final String TAG = ">>>TokenInterceptor";
    private static final boolean DEBUG = false;

    private static final String TOKEN = "Token";
    private static final String ClientType = "ClientType";
    private static final String VERSION = "Version";
    private static final String CODE = "Code";
    private static volatile boolean LoginSuccess = false;//登录成功
    private static volatile boolean tryToLogining = false;//是否正在尝试登录
    private static final Object ObjectLock = new Object();//对象锁



    @Override
    public Response intercept(Chain chain) throws IOException {
        if (DEBUG) {
            LogUtils.d(TAG, "############Token拦截############");
        }
        //添加token到header
        Request request = chain.request();
        request = addParam(request);
        String url = request.url().toString();
        if (DEBUG) {
            LogUtils.d(TAG, "request:" + url);
        }

        //返回的Response
        Response response = chain.proceed(request);
        boolean successful = response.isSuccessful();
        if (successful) {
            //成功
            //是登录,读取token并保存
            if (url.contains(BaseRequests.Login)) {
                LogUtils.d(TAG, "登录接口");
                //保存token
                ResponseBody body = response.body();
                if (body != null) {
                    byte[] bytes = body.bytes();
                    String json = new String(bytes, "UTF-8");
                    try {
                        /*if (DEBUG) {
                            LogUtils.d(TAG, "json:"+json);
                        }*/
                        JsonObject responseData = (JsonObject) new JsonParser().parse(json);
                        int code = responseData.get(CODE).getAsInt();
                        if (code == HttpErrors.STATUS_SUCCESS) {
                            LogUtils.d(TAG, "登录成功");
                            JsonObject data = responseData.getAsJsonObject("Data");
                            if (data != null) {
                                String newToken = data.get(TOKEN).getAsString();
                                if (!StringUtils.isNullOrEmpty(newToken)) {
                                    LogUtils.d(TAG, "保存token=" + newToken);
                                    DataManager.setToken(newToken);
                                    LoginSuccess = true;
                                } else {
                                    LogUtils.e(TAG, "登录没有返回token");
                                }
                            }
                        } else {
                            LogUtils.e(TAG, "登录失败");
                        }

                    } catch (Exception e) {
                        LogUtils.e(TAG, "e=" + e.getMessage());
                        e.printStackTrace();
                    }
                    // 这里值得注意。由于前面value.bytes()把响应流读完并关闭了，所以这里需要重新生成一个response，
                    // 否则数据就无法正常解析了
                    return response.newBuilder()
                            .body(ResponseBody.create(MediaType.parse(ContentType.JSON), bytes))
                            .build();
                }

            }
        } else {
            //请求失败
            int code = response.code();
            if (code == HttpErrors.STATUS_UNAUTHORIZED) {
                //未经授权(没有登录,登录过期)
                if (DEBUG) {
                    LogUtils.e(TAG, HttpErrors.STATUS_UNAUTHORIZED_MESSAGE + request.url());
                }
            }
        }
        return response;
    }

    /**
     * 请求头中添加token
     *
     * @param request
     * @return
     */
  /*  private Request addToken(Request request) {
        String token = DataManager.getInstance().getToken();
        if (token != null) {
            //创建新的请求添加cookie
            LogUtils.d(TAG, "intercept:添加token到header");
            okhttp3.Request.Builder builder = request.newBuilder();
            builder.removeHeader(TOKEN);//防止添加多个同名token
            builder.addHeader(TOKEN, token);
            request = builder.build();
        }
        return request;
    }*/

    /**
     * 添加统一参数在url上
     *
     * @param oldRequest
     * @return
     */
    private Request addParam(Request oldRequest) {
        //添加通用参数到url中
//        HttpUrl.Builder builder = oldRequest.url()
//                .newBuilder()
//                .setEncodedQueryParameter("version", "" + AppManager.getInstance().getVersion())//通用参数版本号
//                .setEncodedQueryParameter("platform", "android");//平台:android
        Request.Builder newBuilder = oldRequest.newBuilder();
        //添加token到header中
        String token = DataManager.getToken();
        if (!StringUtils.isNullOrEmpty(token)) {
            //添加token
            newBuilder.removeHeader(TOKEN);//防止添加多个同名token
            newBuilder.addHeader(TOKEN, token);
            if (DEBUG) {
                LogUtils.d(TAG, "token:"+token);
            }
        }
        //添加通用参数
        //添加ClientType
        newBuilder.removeHeader(ClientType);//防止添加多个同名
        newBuilder.addHeader(ClientType, "1");
        newBuilder.removeHeader(VERSION);//防止添加多个同名
        //创建新请求
        return newBuilder.method(oldRequest.method(), oldRequest.body())
                .url(oldRequest.url())
                .build();
    }


}
